#!/usr/bin/python3

import requests
import json
import openai
import secrets_info

api_key = secrets_info.GPT35_API_KEY
api_base = secrets_info.GPT35_URL_BASE
model="gpt-3.5-turbo-0613"

def get_weather(location):
    openweather_key="9c8051bdbcec4574fa6c00cf831b5d87"
    openweather_url="https://api.openweathermap.org/data/2.5/weather"

    weather_params = {
        "q": location,
        "appid": openweather_key,
        "units": "metric",
        "lang": "zh_cn"
    }
    print("query city: ", location)
    weather_response = requests.get(openweather_url, params=weather_params)
    data = weather_response.json()
    return json.dumps(data)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "查询当前天气函数,根据输入的城市名称,查询对应城市的实时天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市名称,注意,中国的城市需要用对应城市的英文名称代替,例如查询北京市的天气,locale参数需要输入Beijing",
                    },
                },
                "required": ["location"],
            },
        },
    }
]

available_functions = {
    "get_weather": get_weather
}

openai.api_key = api_key
openai.api_base = api_base

def chatgpt(prompt):

    messages = [
        {"role": "user", "content": prompt}
    ]

    # 调用OpenAI ChatCompletion.create函数进行对话生成
    response = openai.ChatCompletion.create(
        model = model,
        tools=tools,
        tool_choice="auto",  # auto is default, but we'll be explicit
        messages = messages
    )

    print('receive response_messages')
    response_message = response.choices[0].message
    tool_calls = response_message.tool_calls

    if tool_calls:
        messages.append(response_message)  # extend conversation with assistant's reply
        for tool_call in tool_calls:
            function_name = tool_call.function.name
            function_to_call = available_functions[function_name]
            function_args = json.loads(tool_call.function.arguments)

            function_response = function_to_call(**function_args)

            messages.append(
                {
                    "tool_call_id": tool_call.id,
                    "role": "tool",
                    "name": function_name,
                    "content": function_response,
                }
            )  # extend conversation with function response

            second_response = openai.ChatCompletion.create(
                model = model,
                messages = messages,
            )  # get a new response from the model where it can see the function response

            print('receive response_messages')    
            second_response_messages = second_response.choices[0].message

    return second_response_messages.content

print(chatgpt("请帮我查询天津的天气"))

